//
// Created by liaohailong on 2025/4/18.
//

#include "HelloRequestHandler.hpp"

HelloRequestHandler::HelloRequestHandler(const char *tag) : logger(tag), fetchers(),
                                                            fetcherMutex(), urlMutex(),
                                                            urls()
{
    logger.i("HelloRequestHandler::HelloRequestHandler(%p)", this);
}

HelloRequestHandler::~HelloRequestHandler()
{
    logger.i("HelloRequestHandler::~HelloRequestHandler(%p)", this);
}


void HelloRequestHandler::addDataFetcher(int fd,
                                         const std::shared_ptr<HelloDataFetcher> &writer)
{
    std::unique_lock<std::mutex> locker(this->fetcherMutex);

    auto find = fetchers.find(fd);
    if (find == fetchers.end())
    {
        fetchers[fd] = writer;
    } else
    {
        logger.e("clientWriters[%d] is already exist", fd);
    }
}

void HelloRequestHandler::removeDataFetcher(int fd)
{
    std::unique_lock<std::mutex> locker(fetcherMutex);

    auto find = fetchers.find(fd);
    if (find != fetchers.end())
    {
        find->second->stop();
    }
    fetchers.erase(fd);
}

void HelloRequestHandler::clearAndWaitAllFetcher()
{
    std::unique_lock<std::mutex> locker(fetcherMutex);
    for (const auto &item: fetchers)
    {
        item.second->stop();
    }
    fetchers.clear();

    // 顺便清除一下 url 列表，容错率高
    clearUrls();
}

void HelloRequestHandler::addUrl(const std::string &url)
{
    std::unique_lock<std::mutex> locker(urlMutex);
    urls.insert(url);
}

void HelloRequestHandler::removeUrl(const std::string &url)
{
    std::unique_lock<std::mutex> locker(urlMutex);
    urls.erase(url);
}

bool HelloRequestHandler::hasUrl(const std::string &url)
{
    std::unique_lock<std::mutex> locker(urlMutex);
    return urls.find(url) != urls.end();
}

void HelloRequestHandler::clearUrls()
{
    std::unique_lock<std::mutex> locker(urlMutex);
    urls.clear();
}
